package com.csiec.clock.model;

import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.csiec.clock.bean.Clock;
import com.csiec.clock.bean.UserInfo;
import com.csiec.clock.bean.clock.BackData;
import com.csiec.clock.bean.result.ResultCode;
import com.csiec.clock.callback.LoginCallBack;
import com.csiec.clock.callback.NewClockCallBack;
import com.csiec.clock.utils.Constant;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class NewModel {

    private final String www = Constant.www;
    private final String newClockInUrl = "/clockin/new";
    private Clock clock;

    //登录的网络请求
    public void newClock(final Clock clock1, final NewClockCallBack callBack) {
        this.clock = clock1;
        Log.d("newClock", "newClock: " + clock1.getType());
        new Thread(() -> {
            try {
                OkHttpClient client = new OkHttpClient();//新建一个OKHttp的对象
                RequestBody body = new FormBody.Builder()
                        .add("title", clock.getTitle())
                        .add("type", clock.getType())
                        .add("startDate", clock.getStartDate())
                        .add("endDate", clock.getEndDate())
                        .add("startTime", clock.getStartTime())
                        .add("endTime", clock.getEndTime())
                        .add("destination", clock.getDestination())
                        .add("positionType", clock.getPositionType())
                        .add("latitude", clock.getLatitude())
                        .add("longitude", clock.getLongitude())
                        .add("range", clock.getRange())
                        .add("information_required", clock.getPositionInformation())
                        .add("information_type", clock.getInformation_type())
                        .build();
                Request request = new Request.Builder()
                        .addHeader("token", UserInfo.getUserInfo().getToken())
                        .url(www + newClockInUrl)
                        .post(body)
                        .build();//创建一个Request对象

                Response response = client.newCall(request).execute();//发送请求获取返回数据
                String responseData = response.body().string();//处理返回的数据

                ResultCode backData = JSONObject.parseObject(responseData, ResultCode.class);

                callBack.onSuccess(backData);

            } catch (Exception e) {
                callBack.onFailed();
                e.printStackTrace();
            }
        }).start();

    }

}
